package com.ifonly.ext.freemarker.directive;

import com.ifonly.ext.freemarker.utils.DirectiveUtils;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

import java.io.IOException;
import java.io.Writer;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-16 15:44
 * @since JDK 1.6
 */
public class TemplateDirectiveBodyOverrideWrapper implements TemplateDirectiveBody, TemplateModel {

    private TemplateDirectiveBody body;
    public TemplateDirectiveBodyOverrideWrapper parentBody;
    public Environment env;

    public TemplateDirectiveBodyOverrideWrapper(TemplateDirectiveBody body,
                                                Environment env) {
        super();
        this.body = body;
        this.env = env;
    }

    @Override
    public void render(Writer out) throws TemplateException, IOException {
        if (body == null) return;
        TemplateDirectiveBodyOverrideWrapper preOverridy = (TemplateDirectiveBodyOverrideWrapper) env.getVariable(DirectiveUtils.OVERRIDE_CURRENT_NODE);
        try {
            env.setVariable(DirectiveUtils.OVERRIDE_CURRENT_NODE, this);
            body.render(out);
        } finally {
            env.setVariable(DirectiveUtils.OVERRIDE_CURRENT_NODE, preOverridy);
        }
    }

}
